const req = require('request-promise');

const request = async ({ url, data = {}, method = 'GET' }) => {
  const option = {
    url,
    method,
  };
  if (method === 'POST') {
    option.data = data;
    option.json = true;
  }

  return req(option)
    .then(json => {
      let ret = json;
      if (typeof json === 'string') {
        try {
          ret = JSON.parse(json);
        } catch (error) {}
      }
      return ret;
    })
    .catch(e => {
      rp.cancel();
      _logger.error(`${url} error::`, e);
      return {
        errcode: -1,
        errmsg: '请求失败',
      };
    });
};

module.exports = request;
